//
//  YPWmcManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/31.
//
/*

 */

import UIKit

@_exported import YPBedrock

@_exported import NSObject_Rx
@_exported import RxCocoa
@_exported import RxSwift

@_exported import HandyJSON
@_exported import Kingfisher
@_exported import SnapKit
@_exported import YPNetwork

// MARK: - [YPWmcManager]

open class YPWmcManager: WmcBaseVM {
    // Open

    /// 通用二级事件代理
    open lazy var delegate: WmcDelegate = {
        let delegate = WmcDelegate()
        return delegate
    }()

    /// 通用二级UI代理
    open lazy var uiDelegate: WmcUIDelegate = {
        let delegate = WmcUIDelegate()
        return delegate
    }()

    /// 是否是独立包
    open var isIndependentPage: Bool {
        return platform == .watermarkCamera
    }

    /// 版本号
    open var version: String {
        if YPWmcManager.shared.isIndependentPage {
            return YPApp.Version
        } else {
            return "2.9.1"
        }
    }

    /// 多媒体版本号
    open var mediaSdkVersion: String {
        return "1.2.0"
    }

    // Public

    /// 单例实例化
    public static let shared: YPWmcManager = {
        let manager = YPWmcManager()
        return manager
    }()

    /// 是否输出Log
    public static var isShowLog: Bool = true {
        didSet { WmcLogManager.isShowLog = isShowLog }
    }

    /// 加载配置
    public static func loadConfig() {
        WmcAppStateManager.shared.config() // app状态管理
        WmcNavigatorManager.shared.config() // 路由管理器
        WmcDateManager.shared.config() // 时间管理器
        WmcMotionManager.shared.config() // 运动管理器
        WmcDBManager.shared.config() // 数据库管理
        WmcFontManager.shared.config() // 字体管理
        WmcAuthorizedManager.shared.config() // 权限
        WmcCLLocationManager.shared.config() // 系统定位
        WmcDecibeManager.shared.config() // 噪音分贝

        // 登录相关
        WmcLoginManager.config { _ in
            WmcDBManager.shared.createUploadQueueTable()
            WmcDBManager.shared.createUploadQueueV2Table()
            WmcDBManager.shared.createCloudAblumInfoTable()
            shared.loginSuccess.onNext(())
            
            // 检查更新
            WmcAppUpdateManager.CheckUpdate()
        }
    }

    /// 切换网络环境
    /// - Parameter type: 网络环境
    public static func switchNetworkEnvironment(_ type: EnvironmentType) {
        shared.environmentType = type

        if let typeNum: Int = WmcUserdefault.object(forKey: .networkEnvironment), let typeEnum = YPWmcManager.EnvironmentType(rawValue: typeNum) {
            if typeEnum != type {
                WmcUserdefault.save(value: type.rawValue, forKey: .networkEnvironment)
            }
        } else {
            WmcUserdefault.save(value: type.rawValue, forKey: .networkEnvironment)
        }
    }

    public static func registerPlatform(_ platform: Platform) {
        shared.platform = platform
    }

    // Internal

    /// 登录成功
    private(set) var loginSuccess: PublishSubject<Void> = .init()

    /// 环境
    var environmentType: EnvironmentType = .release
    /// 宿主平台
    var platform: Platform = .watermarkCamera
    /// 业务id
    var appId: String = "101"
    
    /// 鱼泡请求扩展字段
     var yupaoEextensionHeaders: [String: String] = [:]
     /// 多媒体请求扩展字段
     var mediaExtensionHeaders: [String: String] = [:]
     /// 原php请求扩展字段
     var originExtensionHeaders: [String: String] = [:]
    
    /// 入口来源
    var entry: Int = 1
    /// 水印组类型
    var watermarkGroupType: WatermarkGroupType = .default
    /// 识别水印组类型
    var recognitionWatermarkGroupType: RecognitionWatermarkGroupType = .default
    /// 属性附带表
    var attachedMap: [Int: Any] = [:]

    /// 驱动交互事务管理
    let drivingManager: YPWmcDrivingManager = .shared

    /// 真实对象，可以获取到真实数据
//    let realObject: RealObject = .init()

    /// 推出的cameraVC
    var presentVC: UIViewController?

    /// 消失回调
    var dismissEventBlock: YPBlock.Empty?

    /// 拉起任意一个VC
    /// 内部会自动为该VC进行包装导航等设置
    /// - Parameters:
    ///   - vc: vc
    ///   - animated: 动画
    ///   - presentCompletion: 动画完成回调
    static func present(vc: UIViewController,
                        animated: Bool = true,
                        settingPresentVC: Bool = true,
                        presentCompletion: YPBlock.Empty? = nil)
    {
        // 主线程
        YPGCD.Main {
            let navVC = WmcNavVC(rootViewController: vc)
            navVC.modalPresentationStyle = .fullScreen // 永远填充全屏
            if settingPresentVC {
                shared.presentVC = navVC
            }
            YPApp.CurrentVC?.present(navVC,
                                            animated: animated,
                                            completion: presentCompletion)
        }
    }

    /// 清除所有附加属性
    static func clearAttached() {
        shared.attachedMap = [:]
    }
}

extension YPWmcManager.Platform {
    struct Info {
        /// 来源字段
        var sourceField: String
        /// 业务方标识,用来区分各个业务方
        var business: String
    }

    /// 信息
    var info: Info {
        switch self {
        case .watermarkCamera:
            return .init(sourceField: "gcdkxj_ios", business: "SYXJ")
        case .fishBubble:
            return .init(sourceField: "ios", business: "YPZP")
        case .recordWork:
            return .init(sourceField: "igd", business: "JGJZ")
        case .saas:
            return .init(sourceField: "isaas", business: "GDXT")
        }
    }
}

extension YPWmcManager.WatermarkGroupType {
    struct Info {
        /// 模版类型组
        var templateIds: [Int]?

        /// 键值
        var key: String
    }

    /// 信息
    var info: Info {
        switch self {
        case .default:
            return .init(templateIds: nil, key: "default")
        case .restAssuredRecord:
            return .init(templateIds: [79], key: "recordWork")
        case let .custom(classifyIds: _, templateTypes: templateTypes):
            var templateIds: [Int] = []
            var key = "WatermarkGroupType_\(YPWmcManager.shared.platform)"
            templateTypes.forEach { type in
                templateIds.append(type.rawValue)
                key.append("\(type.rawValue)")
            }
            return .init(templateIds: templateIds, key: key)
        }
    }
}

extension YPWmcManager.RecognitionWatermarkGroupType {
    struct Info {
        /// 模版类型组
        var templateIds: [Int]?

        /// 键值
        var key: String
    }

    /// 信息
    var info: Info {
        switch self {
        case .default:
            return .init(templateIds: [80, 81], key: "recognition")

        case let .custom(classifyIds: _, templateTypes: templateTypes):
            var templateIds: [Int] = []
            var key = "RecognitionWatermarkGroupType_\(YPWmcManager.shared.platform)"
            templateTypes.forEach { type in
                templateIds.append(type)
                key.append("\(type)")
            }
            return .init(templateIds: templateIds, key: key)
        }
    }
}

extension YPWmcManager.ActivityType {
    struct Info {
        /// 活动值
        var activityValue: Int
    }

    /// 信息
    var info: Info {
        switch self {
        case .yp_giveIntegral: return .init(activityValue: 1)
        }
    }
}
